package com.zhu.tool_test.starke.sql;


import com.zhu.tool_test.starke.util.buffer.core.StarkeBuilder;
import lombok.Builder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @author 4everlynn
 * @version V1.0
 * @description
 * @date 2019-09-02
 */
public class SqlBuilder {
    private String table;
    private List<String> fields;
    private Condition condition;

    @Builder
    public static class ConditionItem {
        private String value;
        private boolean fuzzy;
        private int fuzzyType = 0;

        public String build() {
            if (this.fuzzy) {
                if (fuzzyType == 0) {
                    return StarkeBuilder.build(" like %{}%", value);
                } else if (fuzzyType == 1) {
                    return StarkeBuilder.build(" like %{}", value);
                } else if (fuzzyType == 2) {
                    return StarkeBuilder.build(" like {}%", value);
                }
            }
            return StarkeBuilder.build(" = {}", value);
        }
    }


    public static class Condition extends LinkedHashMap<String, ConditionItem> {
        public Condition add(String field, ConditionItem conditionItem) {
            this.put(field, conditionItem);
            return this;
        }

        public String build() {
            StringBuilder builder = new StringBuilder();
            this.forEach((field, condition) -> builder.append(StarkeBuilder.build("{}{}", field, condition.build())));
            return builder.toString();
        }
    }


    public SqlBuilder select(String... fields) {
        this.fields = new ArrayList<>(Arrays.asList(fields));
        return this;
    }

    public SqlBuilder from(String table) {
        this.table = table;
        return this;
    }

    public SqlBuilder where(Condition condition) {
        this.condition = condition;
        return this;
    }

    public String build() {
        return StarkeBuilder.build("select {} from {} where {}", StarkeBuilder
                .buildString(fields, item -> item), table, condition.build());
    }
}
